package com.softeem.iov.advice;

import com.softeem.iov.dto.R;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器增强: 对所有的控制器中数据进行验证
 */
@RestControllerAdvice
public class ValidationAdviceController {
    /**
     * 统一异常处理(数据绑定异常)
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class})
    public R handlerDataExp(BindException e) {
        //获取异常字段信息
        List<FieldError> errs = e.getFieldErrors();
        Map<String,String> errInfo = new HashMap<>();
        errs.forEach(fe -> {
            //将异常信息添加到map集合
            errInfo.put(fe.getField(),fe.getDefaultMessage());
        });
        return R.fail().setData(errInfo);
    }
}
